/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.ufmg.ubicomp.droidguide.controller;

import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author wpjr
 */
public abstract class ServletAbstract extends HttpServlet {

    protected void logMessage(String m)
    {
        Logger.getLogger(getClass().getName()).log(Level.INFO, m);      
    }
    
    protected void listParametersFromRequest(HttpServletRequest request) {

        Map mapa = request.getParameterMap();

        for (Object s : mapa.keySet()) {
            String[] m = (String[]) mapa.get(s);
            logMessage(s + ": " + m[0]);
        }
    }
    
    protected void showErrorScreen(HttpServletRequest request, 
            HttpServletResponse response, Exception e)
    {
        e.printStackTrace();
        request.setAttribute("mensagemErro", e.getClass().getName() + ": " +
                e.getMessage());
        try {
            forwardToPage(request, response, "/erro.jsp");
        } catch (IOException ex) {
            Logger.getLogger(ServletAbstract.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ServletException ex) {
            Logger.getLogger(ServletAbstract.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    protected void forwardToPage(final HttpServletRequest request,
            final HttpServletResponse response,
            String url)
            throws IOException, ServletException {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    protected void redirectToPage(final HttpServletRequest request,
            final HttpServletResponse response,
            String url)
            throws IOException, ServletException {
        response.sendRedirect(url);
    }
    
    protected void addToSession(HttpServletRequest request, Object obj, Object key)
    {
    	request.getSession().setAttribute(key.toString(), obj);
    }
    
    protected Object getFromSession(HttpServletRequest request, Object key)
    {
    	return request.getSession().getAttribute(key.toString());
    }
    
}
